
/**   
 * @Title: SignUpActivity.java 
 * @Package: com.rename.icode.activity 
 * @Description: Administrator版权所有
 * @author Administrator  
 * @date 2015-2-12 下午1:21:25 
 * @version  
 */


package com.rename.icode.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.rename.icode.R;
import com.rename.icode.model.User;
import com.rename.icode.task.LoginTask;
import com.rename.icode.task.SignUpTask;
import com.rename.icode.utils.LogUtil;
import com.rename.icode.utils.StringUtil;
import com.rename.icode.view.ClearEditText;
import com.rename.icode.worker.Worker;

/** 
 * @Description 实现了...功能
 * @author Administrator
 * @date 2015-2-12 下午1:21:25 
 * @version V1.0
 */

public class SignUpActivity extends ActivitySupport {
	
	private static final String TAG = "SignUpActivity";

	private boolean showVerificationLayout = false;
	
	private final static int SIGNUP_SUCC = 0;
	private final static int SIGNUP_FAIL = -1;
	
	private final static int SMS_CODE_RESEND_DURATION = 60;
	//
    private long mExitTime = 0;   
	private User newUser = null;
	private ImageView loginImg = null;

	private LinearLayout mCellphoneStepLayout = null;
	private LinearLayout mCodeVerifyStepLayout = null;
	private LinearLayout mUserInfoStepLayout = null;
	
	private Button mSignUpCfmBtn = null;
	private Button mResendBtn = null;
	private Button mVerifyBtn = null;
	private Button mSignUpCmpBtn = null;
	private ClearEditText mCellphoneText = null;
	private ClearEditText mVerifyCodeText = null;
	private ClearEditText mNickNameText = null;
	private ClearEditText mPasswordText = null;
	private TextView mSmsSendTipsTxt = null;
	private RadioGroup mGenderRadioGrp = null;
	private RadioButton mMaleRadio = null;
	private RadioButton mFemaleRadio = null;
	
	private String mGender = "";
	
	private Worker mSmsCodeSendWorker = null;
	private String mSignUpPhoneNO = "";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_signup);
		
		LogUtil.i(TAG, "登录activity");
		init();
		
	}

	@Override
	protected void onResume() {
		
		super.onResume();
		if(showVerificationLayout){
			
		}
	}
	@Override
	protected void onPause() {
		super.onPause();
		Log.i(TAG, "signupActivity onPause():showVerificationLayout:"+showVerificationLayout);
		
	}
	@Override
	public void onDestroy() {
		super.onDestroy();
		mSmsCodeSendWorker.destroy();
		showVerificationLayout = false;
	}
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		outState.putBoolean("showVerificationLayout", showVerificationLayout);
	}
	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		showVerificationLayout = savedInstanceState.getBoolean("showVerificationLayout");
		Log.i(TAG, TAG +"onRestoreInstanceState"+" showVerificationLayout: "+showVerificationLayout);
	}
	
	protected void init() {
		getICodeApplication().addActivity(this);

		loginImg = (ImageView) findViewById(R.id.loading_img);

		mCellphoneStepLayout = (LinearLayout) findViewById(R.id.signup_cellphone_layout);
		mCodeVerifyStepLayout = (LinearLayout) findViewById(R.id.signup_verifycode_layout);
		mUserInfoStepLayout = (LinearLayout) findViewById(R.id.signup_userinfo_layout);

		mSignUpCfmBtn = (Button) findViewById(R.id.signup_cfm_btn);//注册
		mSignUpCmpBtn = (Button) findViewById(R.id.signup_cmp_btn);//完成注册
		
		mResendBtn = (Button) findViewById(R.id.resend_btn);//重发
		mVerifyBtn = (Button) findViewById(R.id.verify_btn);//验证

		mCellphoneText = (ClearEditText) findViewById(R.id.signup_cellphone_input);
		mVerifyCodeText = (ClearEditText) findViewById(R.id.verify_code_input);
		mSmsSendTipsTxt = (TextView) findViewById(R.id.verify_code_tips_txt);

		mNickNameText = (ClearEditText) findViewById(R.id.signup_name_input);
		mNickNameText.setRawInputType(InputType.TYPE_CLASS_TEXT); 
		
		mPasswordText = (ClearEditText) findViewById(R.id.signup_password_input);
		mPasswordText.setRawInputType(InputType.TYPE_CLASS_TEXT); 
		
		mGenderRadioGrp = (RadioGroup) findViewById(R.id.gender_radio_grp);
	    mMaleRadio = (RadioButton) findViewById(R.id.gender_radio_male);
	    mFemaleRadio = (RadioButton) findViewById(R.id.gender_radio_female); 
	    
	    mGenderRadioGrp.setOnCheckedChangeListener(new 
    		RadioGroup.OnCheckedChangeListener() { 
				@Override 
				public void onCheckedChanged(RadioGroup group, int checkedId) { 
					//TODO:选择性别
					if (checkedId == mMaleRadio.getId()) {
//						mGender = User.MALE;
					}
					else if (checkedId == mFemaleRadio.getId()) {
//						mGender = User.FEMALE;
					}
				}
    		}
	    ); 
	    
	    mSignUpCfmBtn.setOnClickListener(new View.OnClickListener() { // 注册按钮
			@Override
			public void onClick(View v) {
				LogUtil.i(TAG, "点击注册按钮");
				//TODO:检查是否为手机号码，然后注册，发送验证码
				if(checkCellphone()) {
					LogUtil.i(TAG, "输入的是手机号");
					showSendVerificationCodeDialog(mCellphoneText.getText().toString().trim());
				}else {
					showToast("请输入手机号");
				}
			}
		});
	    
	    mResendBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//TODO:重发验证码
				
			}
		});
	    
	    mVerifyBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//TODO:验证验证码
				Log.i(TAG, "verify: " + mSignUpPhoneNO + ", " +
						mVerifyCodeText.getText().toString().trim());
				
			}
		});
	    
		
	    mSignUpCmpBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//TODO:完成注册，登录
				if (checkUserInfo()) {
					String nickname = mNickNameText.getText().toString().trim();
					String password = mPasswordText.getText().toString().trim();
					String phone = mSignUpPhoneNO;
					
					newUser = new User();
					newUser.setName(nickname);
					newUser.setPassword(password);
					newUser.setPhone(phone);
					
					Log.d(TAG, "start signup task");
					SignUpTask task = new SignUpTask(SignUpActivity.this);
					task.initUser(newUser);
					task.execute();
				}
			}
		});
	    
	    mSmsCodeSendWorker = new Worker();
	    mSmsCodeSendWorker.initilize("SMS Code Sender");

	}
	
	private void showSendVerificationCodeDialog(final String cellphone) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getResources().getString(R.string.send_sms_code_tips))
				.setMessage(cellphone)
				.setCancelable(false)
				.setPositiveButton(getResources().getString(R.string.confirm),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								// 这关于手机号码验证，以及发送短信验证码都是模拟的没有实际效果，
								mSignUpPhoneNO = cellphone;
								sendSmsVerificationCode(cellphone); // 发送手机短信验证码
								
								// 直接跳到signup_userinfo_layout界面
								changeViewToShow(2);
								LogUtil.i(TAG, "发送验证码");
							}
						})
				.setNegativeButton(getResources().getString(R.string.cancel),
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
		AlertDialog alert = builder.create();
		alert.show();
	}
	
	/**
	 * 
	 * @Description 选择显示的界面
	 * @author Administrator
	 * @param which
	 */
	private void changeViewToShow(int which){
		switch (which) {
		case 0: // signup_cellphone_layout
			mCellphoneStepLayout.setVisibility(View.VISIBLE);
			mCodeVerifyStepLayout.setVisibility(View.GONE);
			mUserInfoStepLayout.setVisibility(View.GONE);
			break;
		case 1: // signup_verifycode_layout
			mCellphoneStepLayout.setVisibility(View.GONE);
			mCodeVerifyStepLayout.setVisibility(View.VISIBLE);
			mUserInfoStepLayout.setVisibility(View.GONE);
			break;
		case 2: // signup_userinfo_layout
			mCellphoneStepLayout.setVisibility(View.GONE);
			mCodeVerifyStepLayout.setVisibility(View.GONE);
			mUserInfoStepLayout.setVisibility(View.VISIBLE);
			break;
		default:
			break;
		}
	}
	
    
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
        	switch(msg.what) {
        	case SIGNUP_SUCC:
    			showToast(getResources().getString(R.string.signup_success));
    			LoginTask task = new LoginTask(SignUpActivity.this, (AnimationDrawable) loginImg.getBackground());
    			task.execute();
            	
                super.handleMessage(msg);
        		break;
        	case SIGNUP_FAIL:
        		showToast(getResources().getString(R.string.signup_fail));
        		changeViewToShow(0); // 登录失败，从头再注册一次
        		break;
        	}

        }
    };
    
    public void sendSmsVerificationCode(String cellphone) {

    }
    
    public void notifySignUpSucc() {
    	handler.sendEmptyMessage(SIGNUP_SUCC);
    }
    
    public void notifySignUpFail(){
    	handler.sendEmptyMessage(SIGNUP_FAIL);
    }
    
	/**
	 * 
	 * 
	 * @return
	 * @author xuweinan
	 * @update 2014-4-8
	 */
	private boolean checkCellphone() {
//		return ValidateUtil.isMobileNumber(mCellphoneText);
		if(StringUtil.empty(mCellphoneText.getText().toString().trim())){
			return false;
		}
		return true;
	}
	
	/**
	 * 
	 * 
	 * @return
	 * @author xuweinan
	 * @update 2014-4-8
	 */
	private boolean checkUserInfo() {
		boolean checked = false;
//		checked = (!ValidateUtil.isEmpty(mNickNameText,getResources().getString(R.string.nickname)) && !ValidateUtil
//				.isEmpty(mPasswordText, getResources().getString(R.string.password)));
		
		// 判断是否为空
		checked = (!StringUtil.empty(mNickNameText.getText())) && (!StringUtil.empty(mPasswordText.getText()));
		
		if (checked) {
			String nickname = mNickNameText.getText().toString().trim();
			String password = mPasswordText.getText().toString().trim();
			if (nickname.length() > 15) {
				showToast(getResources().getString(R.string.nickname_invalid));
				return false;
			}
			
			if (password.length() > 15 && password.length() < 6) {
				showToast(getResources().getString(R.string.pwd_length_less));
				return false;
			}

			return true;
		}
		else {
			showToast(getResources().getString(R.string.nickname_password_null));
			return false;
		}
	}
	
	/**
	 */
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exit() {
        if ((System.currentTimeMillis() - mExitTime) > 2000) {
            showToast( getResources().getString(R.string.exit_sign_click_again));
            mExitTime = System.currentTimeMillis();
        } else {
        	getICodeApplication().exit();
        }
    }
	
}
